<template>
  <s-layout>
    <!-- 筛选和搜索区域 -->
    <view class="filter-container">
      <!-- 搜索框 -->
      <view class="search-box">
        <view class="search-input-wrapper">
          <fui-icon name="search" :size="36" color="#BDBDBD"></fui-icon>
          <input
            v-model="searchKeyword"
            type="text"
            placeholder="搜索任务名称"
            @input="handleSearch"
            class="search-input"
          />
          <view class="clear-btn" v-if="searchKeyword" @tap="clearSearch">
            <fui-icon name="close-fill" :size="28" color="#BDBDBD"></fui-icon>
          </view>
        </view>

        <!-- 测试按钮 - 仅开发使用 -->

        <!-- <view class="filter-options">
          <view class="filter-item" @tap="showStatusFilter = true">
            <text>状态</text>
            <fui-icon name="filter" :size="28" color="#666"></fui-icon>
          </view>
          <view class="filter-divider"></view>
          <view class="filter-item" @tap="showSortOptions = true">
            <text>排序</text>
            <fui-icon name="sort" :size="28" color="#666"></fui-icon>
          </view>
        </view> -->
      </view>

      <!-- 状态标签 -->
      <!-- <scroll-view scroll-x class="status-tags" >
        <view class="tag-container">
          <view 
            class="status-tag"
            :class="{'active-tag': activeTab === index}"
            v-for="(tab, index) in filterTabs" 
            :key="index"
            @tap="setActiveTab(index)"
          >
            <view class="tag-dot" v-if="index !== 0" :style="getTagColor(index)"></view>
            <text>{{ tab }}</text>
          </view>
        </view>
      </scroll-view> -->
    </view>

    <!-- 任务列表 -->
    <scroll-view scroll-y class="task-list">
      <view
        v-for="(task, index) in filteredTasks"
        :key="index"
        class="task-card"
        @click="navigateToTaskDetail(task)"
      >
        <!-- 类型和状态标签 -->
        <view class="card-header">
          <view
            class="task-type-tag"
            :style="{
              backgroundColor: task.typeColor + '15',
              color: task.typeColor,
              borderColor: task.typeColor,
            }"
          >
            {{ task.type }}
          </view>
          <view class="status-pill" :class="getStatusClass(task.status)">
            <view class="status-dot"></view>
            <text>{{ task.status }}</text>
          </view>
        </view>

        <view class="task-title">{{ task.name }}</view>

        <view class="task-info">
          <view class="info-row">
            <view class="info-item">
              <fui-icon name="calendar" :size="32" color="#5289ff"></fui-icon>
              <text>{{ task.startTime }}</text>
            </view>
            <view class="separator">至</view>
            <view class="info-item">
              <fui-icon
                name="calendar-check"
                :size="32"
                color="#5289ff"
              ></fui-icon>
              <text>{{ task.endTime }}</text>
            </view>
          </view>

          <!-- <view class="score-row">
            <view class="score-box">
              <text>评分</text>
              <view class="score-badge" :class="getScoreClass(task.score)">{{
                task.score
              }}</view>
            </view>
            <view class="arrow-right">
              <fui-icon name="arrowright" :size="36" color="#BDBDBD"></fui-icon>
            </view>
          </view> -->
        </view>
      </view>

      <!-- 空状态 -->
      <view v-if="filteredTasks.length === 0" class="empty-state">
        <image
          src="/static/empty.png"
          mode="aspectFit"
          class="empty-image"
        ></image>
        <text class="empty-text">暂无任务数据</text>
        <view class="empty-desc">请尝试更换筛选条件</view>
      </view>
    </scroll-view>

    <!-- 状态筛选弹出层 -->
    <fui-drawer
      :show="showStatusFilter"
      position="bottom"
      @close="showStatusFilter = false"
    >
      <view class="drawer-content">
        <view class="drawer-header">
          <text class="drawer-title">选择状态</text>
          <view class="drawer-close" @tap="showStatusFilter = false">
            <fui-icon name="close" :size="36" color="#333"></fui-icon>
          </view>
        </view>
        <view class="filter-list">
          <view
            class="filter-option"
            v-for="(tab, index) in filterTabs"
            :key="index"
            @tap="selectFilterOption(index)"
          >
            <text>{{ tab }}</text>
            <view class="option-selected" v-if="activeTab === index">
              <fui-icon
                name="checkbox-fill"
                :size="40"
                color="#5289ff"
              ></fui-icon>
            </view>
          </view>
        </view>
        <view class="drawer-footer">
          <view class="drawer-btn cancel" @tap="showStatusFilter = false"
            >取消</view
          >
          <view class="drawer-btn confirm" @tap="confirmFilter">确定</view>
        </view>
      </view>
    </fui-drawer>

    <!-- 排序选项弹出层 -->
    <fui-drawer
      :show="showSortOptions"
      position="bottom"
      @close="showSortOptions = false"
    >
      <view class="drawer-content">
        <view class="drawer-header">
          <text class="drawer-title">排序方式</text>
          <view class="drawer-close" @tap="showSortOptions = false">
            <fui-icon name="close" :size="36" color="#333"></fui-icon>
          </view>
        </view>
        <view class="filter-list">
          <view
            class="filter-option"
            v-for="(option, index) in sortOptions"
            :key="index"
            @tap="selectSortOption(option)"
          >
            <text>{{ option }}</text>
            <view class="option-selected" v-if="currentSort === option">
              <fui-icon
                name="checkbox-fill"
                :size="40"
                color="#5289ff"
              ></fui-icon>
            </view>
          </view>
        </view>
        <view class="drawer-footer">
          <view class="drawer-btn cancel" @tap="showSortOptions = false"
            >取消</view
          >
          <view class="drawer-btn confirm" @tap="confirmSort">确定</view>
        </view>
      </view>
    </fui-drawer>

    <!-- 浮动添加按钮 -->
    <!-- <view class="add-button" @click="createNewTask">
      <fui-icon name="plus" :size="48" color="#fff"></fui-icon>
    </view> -->
  </s-layout>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import sheep from "@/sheep";
import { onLoad } from "@dcloudio/uni-app";

// 搜索关键词
const searchKeyword = ref("");

// 筛选相关状态
const showStatusFilter = ref(false);
const showSortOptions = ref(false);

// 标签筛选
const filterTabs = ref(["全部", "进行中", "已完成", "未开始"]);
const activeTab = ref(0);
const tempActiveTab = ref(0); // 临时存储选择的标签

// 排序选项
const sortOptions = ref(["创建时间", "结束日期", "评分"]);
const currentSort = ref("创建时间");
const tempSort = ref("创建时间"); // 临时存储选择的排序

// 任务数据
const tasks = ref([
  {
    id: 1,
    name: "消防设施季度检查",
    status: "进行中",
    type: "安全检查",
    typeColor: "#1890ff",
    startTime: "2023-10-01",
    endTime: "2023-12-31",
    score: 85,
    progress: 65,
    description: "对所有消防设施进行全面检查，确保正常运行",
  },
  {
    id: 2,
    name: "员工消防安全培训",
    status: "已完成",
    type: "培训",
    typeColor: "#52c41a",
    startTime: "2023-09-15",
    endTime: "2023-09-20",
    score: 92,
    progress: 100,
    description: "对全体员工进行消防安全知识培训与演练",
  },
  {
    id: 3,
    name: "消防应急预案演练",
    status: "未开始",
    type: "演练",
    typeColor: "#fa8c16",
    startTime: "2023-11-15",
    endTime: "2023-11-20",
    score: 0,
    progress: 0,
    description: "模拟火灾场景下的应急疏散与处置",
  },
  {
    id: 4,
    name: "危险品储存检查",
    status: "进行中",
    type: "安全检查",
    typeColor: "#1890ff",
    startTime: "2023-10-10",
    endTime: "2023-10-25",
    score: 78,
    progress: 45,
    description: "检查危险品存储是否符合安全标准",
  },
  {
    id: 5,
    name: "消防安全责任制考核",
    status: "已完成",
    type: "评估",
    typeColor: "#722ed1",
    startTime: "2023-08-01",
    endTime: "2023-08-15",
    score: 88,
    progress: 100,
    description: "对各部门消防安全责任落实情况进行考核",
  },
]);

// 根据选中的标签筛选任务
const filteredTasks = computed(() => {
  let result = [...tasks.value];

  // 关键词搜索过滤
  if (searchKeyword.value) {
    result = result.filter(
      (task) =>
        task.name.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
        task.description
          .toLowerCase()
          .includes(searchKeyword.value.toLowerCase())
    );
  }

  // 状态标签过滤
  if (activeTab.value !== 0) {
    // 不是"全部"选项
    const statusMap = {
      1: "进行中",
      2: "已完成",
      3: "未开始",
    };
    result = result.filter(
      (task) => task.status === statusMap[activeTab.value]
    );
  }

  // 排序
  switch (currentSort.value) {
    case "创建时间":
      result.sort((a, b) => new Date(b.startTime) - new Date(a.startTime));
      break;
    case "结束日期":
      result.sort((a, b) => new Date(a.endTime) - new Date(b.endTime));
      break;
    case "评分":
      result.sort((a, b) => b.score - a.score);
      break;
  }

  return result;
});

// 获取标签颜色
const getTagColor = (index) => {
  const colors = {
    1: { background: "#1890ff" },
    2: { background: "#52c41a" },
    3: { background: "#fa8c16" },
  };
  return colors[index] || { background: "#5289ff" };
};

// 获取任务状态样式类
const getStatusClass = (status) => {
  const statusMap = {
    未开始: "status-notstarted",
    进行中: "status-pending",
    已完成: "status-completed",
    已延期: "status-delayed",
  };
  return statusMap[status] || "status-notstarted";
};

// 清空搜索
const clearSearch = () => {
  searchKeyword.value = "";
  handleSearch();
};

// 设置当前选中的标签
const setActiveTab = (index) => {
  activeTab.value = index;
  showStatusFilter.value = false;
};

// 选择筛选选项
const selectFilterOption = (index) => {
  tempActiveTab.value = index;
};

// 确认筛选
const confirmFilter = () => {
  activeTab.value = tempActiveTab.value;
  showStatusFilter.value = false;
};

// 选择排序选项
const selectSortOption = (option) => {
  tempSort.value = option;
};

// 确认排序
const confirmSort = () => {
  currentSort.value = tempSort.value;
  showSortOptions.value = false;
};

// 处理排序变化
const handleSortChange = (e) => {
  currentSort.value = sortOptions.value[e.detail.value];
};

// 处理搜索
const handleSearch = () => {
  // 直接依赖 computed 属性，不需要额外处理
};

// 跳转到任务详情页
const navigateToTaskDetail = (task) => {
  uni.navigateTo({
    url: `/pages/qy/task/detail?task_id=${task.id}&company_id=${sheep.$store("user").userInfo.company_id}`,
  });
};

// 创建新任务
const createNewTask = () => {
  uni.showToast({
    title: "新建任务功能即将上线",
    icon: "none",
  });
};

// 获取评分对应的样式类
const getScoreClass = (score) => {
  if (score >= 90) return "score-excellent";
  if (score >= 80) return "score-good";
  if (score >= 60) return "score-average";
  return "score-poor";
};

// 获取任务数据
onMounted(() => {
  // 这里可以添加从API获取任务数据的逻辑
  tempActiveTab.value = activeTab.value;
  tempSort.value = currentSort.value;
});

// 处理任务数据格式
const formatTaskData = (task) => {
  // 任务类型映射
  const typeMap = {
    "1": "区域",
    "2": "行业",
    "3": "单位",
  };
  
  // 任务类型颜色映射
  const typeColorMap = {
    "1": "#1890ff",
    "2": "#52c41a",
    "3": "#722ed1",
    "4": "#fa8c16",
    "5": "#bdbdbd"
  };
  
  // 任务状态映射 (t_status: 0-未开始, 1-进行中, 2-已完成, 3-已延期)
  const statusMap = {
    "0": "未开始",
    "1": "进行中", 
    "2": "已完成",
  };
  
  // 计算评分（示例逻辑）
  let score = 0;
  if (task.t_state === "2") { // 已完成
    score = 85 + Math.floor(Math.random() * 15); // 85-100之间
  } else if (task.t_state === "1") { // 进行中
    score = 60 + Math.floor(Math.random() * 25); // 60-85之间
  } else if (task.t_state === "3") { // 已延期
    score = 40 + Math.floor(Math.random() * 20); // 40-60之间
  } else { // 未开始
    score = 0;
  }
  
  return {
    id: task.t_id,
    name: task.t_name,
    status: statusMap[task.t_state] || "未开始",
    type: typeMap[task.t_type] || "其他",
    typeColor: typeColorMap[task.t_type] || "#bdbdbd",
    startTime: task.t_s_date || "",
    endTime: task.t_e_date || "",
    score: score,
    description: task.t_describe || "",
    // 其他字段
    createTime: task.createtime,
    year: task.t_year,
    province: task.province,
    city: task.city,
    county: task.county
  };
};

// 加载测试数据
const loadTestData = () => {
  const testTask = {
    city: "2",
    county: "0",
    createtime: "2025-04-12 21:36:25",
    del_type: "0",
    lev: "4",
    province: "1",
    t_describe: "单位评估",
    t_e_date: "2025-05-15",
    t_id: "7",
    t_name: "单位评估",
    t_s_date: "2025-04-12",
    t_state: 1,
    t_status: "0",
    t_type: "3",
    t_year: "2025",
    township: "0",
    updatetime: "2025-04-12 21:36:25",
    user_id: "2",
    version_id: "3",
    village: "0"
  };
  
  // 创建多个测试任务，包括不同状态
  const testTasks = [
    testTask,
    {
      ...testTask,
      t_id: "8",
      t_name: "消防演练",
      t_status: "1", // 进行中
      t_type: "4",
      t_s_date: "2025-03-10",
      t_e_date: "2025-06-10",
    },
    {
      ...testTask,
      t_id: "9",
      t_name: "安全检查",
      t_status: "2", // 已完成
      t_type: "1",
      t_s_date: "2025-01-15",
      t_e_date: "2025-03-30",
    }
  ];
  
  tasks.value = testTasks.map(task => formatTaskData(task));
  
  uni.showToast({
    title: "已加载示例数据",
    icon: "none"
  });
};

onLoad(() => {
  // 正常API调用获取任务列表
  const params = {
    company_id: sheep.$store("user").userInfo.company_id,
  };
  
  sheep.$api.qy_index.getTaskList(params).then((res) => {
    // 处理接口返回的任务数据
    if (res && res.taskList && Array.isArray(res.taskList)) {
      const formattedTasks = res.taskList.map(task => formatTaskData(task));
      tasks.value = formattedTasks;
    }
  }).catch(err => {
    console.error('获取任务列表失败:', err);
    // API调用失败时显示空状态
  });
});
</script>

<style lang="scss">
page {
  background-color: #f7f8fc;
}

/* 筛选区域样式 */
.filter-container {
  background-color: #fff;
  padding-bottom: 10rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
}

.search-box {
  padding: 0rpx 20rpx;
}

.search-input-wrapper {
  display: flex;
  align-items: center;
  background-color: #f5f7fa;
  border-radius: 40rpx;
  padding: 10rpx 24rpx;
  margin-bottom: 24rpx;
}

.search-input {
  flex: 1;
  height: 60rpx;
  margin-left: 16rpx;
  font-size: 28rpx;
  color: #333;
}

.clear-btn {
  padding: 8rpx;
}

.filter-options {
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.filter-item {
  display: flex;
  align-items: center;
  padding: 4rpx 20rpx;
  font-size: 28rpx;
  color: #666;
}

.filter-item text {
  margin-right: 10rpx;
}

.filter-divider {
  width: 2rpx;
  height: 30rpx;
  background-color: #e0e0e0;
}

.status-tags {
  padding: 0 24rpx;
  white-space: nowrap;
}

.tag-container {
  display: inline-flex;
  padding: 8rpx 0;
}

.status-tag {
  display: inline-flex;
  align-items: center;
  padding: 12rpx 24rpx;
  margin-right: 20rpx;
  font-size: 26rpx;
  border-radius: 40rpx;
  background-color: #f5f7fa;
  color: #666;
  transition: all 0.3s;
}

.active-tag {
  background-color: #e6f1ff;
  color: #5289ff;
  font-weight: 500;
}

.tag-dot {
  width: 12rpx;
  height: 12rpx;
  border-radius: 50%;
  margin-right: 8rpx;
}

/* 任务列表样式 */
.task-list {
  padding: 24rpx;
  height: calc(100vh - 240rpx);
}

.task-card {
  background-color: #fff;
  border-radius: 20rpx;
  padding: 24rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16rpx;
}

.task-type-tag {
  padding: 6rpx 16rpx;
  font-size: 24rpx;
  border-radius: 8rpx;
  border: 2rpx solid;
}

.status-pill {
  display: flex;
  align-items: center;
  padding: 4rpx 16rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
}

.status-dot {
  width: 12rpx;
  height: 12rpx;
  border-radius: 50%;
  margin-right: 8rpx;
}

.status-completed {
  background-color: #e6f7ff;
  color: #1890ff;
  .status-dot {
    background-color: #1890ff;
  }
}

.status-pending {
  background-color: #fff7e6;
  color: #fa8c16;
  .status-dot {
    background-color: #fa8c16;
  }
}

.status-notstarted {
  background-color: #f5f5f5;
  color: #666;
  .status-dot {
    background-color: #666;
  }
}

.status-delayed {
  background-color: #fff1f0;
  color: #f5222d;
  .status-dot {
    background-color: #f5222d;
  }
}

.task-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 20rpx;
  line-height: 1.4;
}

.task-info {
  position: relative;
}

.info-row {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
}

.info-item {
  display: flex;
  align-items: center;
  font-size: 26rpx;
  color: #666;
}

.info-item text {
  margin-left: 8rpx;
}

.separator {
  margin: 0 16rpx;
  color: #999;
  font-size: 24rpx;
}

.score-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 20rpx;
  border-top: 2rpx dashed #eee;
}

.score-box {
  display: flex;
  align-items: center;
}

.score-box text {
  font-size: 28rpx;
  color: #666;
  margin-right: 16rpx;
}

.score-badge {
  padding: 6rpx 16rpx;
  font-size: 30rpx;
  font-weight: 600;
  border-radius: 8rpx;
}

.score-excellent {
  background-color: #f6ffed;
  color: #52c41a;
}

.score-good {
  background-color: #e6f7ff;
  color: #1890ff;
}

.score-average {
  background-color: #fff7e6;
  color: #fa8c16;
}

.score-poor {
  background-color: #fff1f0;
  color: #f5222d;
}

/* 空状态样式 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
}

.empty-image {
  width: 240rpx;
  height: 240rpx;
  margin-bottom: 20rpx;
}

.empty-text {
  font-size: 32rpx;
  color: #333;
  margin-bottom: 10rpx;
}

.empty-desc {
  font-size: 26rpx;
  color: #999;
}

/* 浮动添加按钮 */
.add-button {
  position: fixed;
  right: 40rpx;
  bottom: 100rpx;
  width: 110rpx;
  height: 110rpx;
  border-radius: 50%;
  background: linear-gradient(135deg, #5289ff, #3460c2);
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 6rpx 16rpx rgba(82, 137, 255, 0.4);
  z-index: 99;
}

/* 抽屉样式 */
.drawer-content {
  padding: 30rpx;
  border-radius: 30rpx 30rpx 0 0;
  background-color: #fff;
}

.drawer-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 30rpx;
  border-bottom: 2rpx solid #f0f0f0;
}

.drawer-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
}

.drawer-close {
  padding: 10rpx;
}

.filter-list {
  padding: 30rpx 0;
  max-height: 600rpx;
  overflow-y: auto;
}

.filter-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx 20rpx;
  border-bottom: 2rpx solid #f5f5f5;
  font-size: 28rpx;
  color: #333;
}

.filter-option:last-child {
  border-bottom: none;
}

.drawer-footer {
  display: flex;
  justify-content: space-between;
  padding-top: 30rpx;
  border-top: 2rpx solid #f0f0f0;
}

.drawer-btn {
  width: 48%;
  height: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 40rpx;
  font-size: 28rpx;
}

.cancel {
  background-color: #f5f7fa;
  color: #666;
}

.confirm {
  background-color: #5289ff;
  color: #fff;
}

.dev-button {
  margin-bottom: 16rpx;
  padding: 12rpx 20rpx;
  background-color: #722ed1;
  color: #fff;
  text-align: center;
  font-size: 26rpx;
  border-radius: 10rpx;
}
</style>
